/**
 * 计算hex字节长度
 * @param {Object} hexString
 */
export function hexByteLength(hexString) {
	let byteLength = hexString.length / 2;

	// If the hex string contains characters greater than '7F' (ASCII DEL),
	// it will need an extra byte to encode the MSB.
	for (let i = 0; i < hexString.length; i += 2) {
		const num = parseInt(hexString.substr(i, 2), 16);
		if (num > 249) byteLength++;
	}

	return decToHex(byteLength, 2);
}

/**
 * 10进制转16补0
 * @param {*} decNumber 
 * @param {*} length 
 * @returns 
 */
export function decToHex(decNumber, length) {
	let hex = decNumber.toString(16);
	if (hex.length < length) {
		hex = ('0'.repeat(length) + hex).slice(-length);
	}
	return hex;
}

/**
 * 累加16进制
 * @param {Object} commandType
 * @param {Object} commandOpcode
 * @param {Object} commandLoad
 */
export function addDemoHexBytes(commandType, commandOpcode, commandLoad) {
    var sum = parseInt(commandType, 16) + parseInt(commandOpcode, 16);
    if (commandLoad != null) {
        var arr = commandLoad.match(/.{1,2}/g);
        for (var i in arr) {
            sum = sum + parseInt(arr[i], 16);
        }
    }

    // 将结果转换回十六进制字符串
    var result = sum.toString(16).padStart(2, '0'); // 使用padStart确保单个数字前补零
    return result;
}

/**
 * 16转化2进制
 * @param {Object} value
 */
export function hexToBinary(value) {
	return parseInt(value, 16).toString(2);;
}

/**
 * 将十六进制字符串转换为 ArrayBuffer 对象
 * @param {Object} hexString
 */
export function hexStringToArrayBuffer(hexString) {
  var buffer = new ArrayBuffer(hexString.length / 2);
  var view = new DataView(buffer);
  for (var i = 0; i < hexString.length; i += 2) {
    var high = parseInt(hexString.charAt(i), 16);
    var low = parseInt(hexString.charAt(i + 1), 16);
    view.setUint8(i / 2, (high << 4) + low);
  }
  return buffer;
}

/**
 * ArrayBuffer 对象 转换为 十六进制字符串
 * @param {Object} buffer
 */
export function ab2hex(buffer) {
  const hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('')
}

/**
 * 单精度浮点数转化hex
 * @param {*} floatNum 
 * @returns 
 */
export function floatToHex(floatNum) {
    // 使用位操作将浮点数转换为32位二进制表示
    const buffer = new ArrayBuffer(4);
    new DataView(buffer).setFloat32(0, floatNum, false); // false表示使用小端
    const hex = Array.prototype.map.call(
        new Uint8Array(buffer),
        (byte) => `00${byte.toString(16)}`.slice(-2)
    ).join('');
    return hex;
}

/**
 * hex转化为单精度浮点数
 * @param {*} hexString 
 * @returns 
 */
export function hexToFloat(hexString) {
    // 将十六进制字符串转换为数字
    const number = parseInt(hexString, 16);

    // 创建一个ArrayBuffer
    const buffer = new ArrayBuffer(4);

    // 创建一个DataView来操作这个buffer
    const view = new DataView(buffer);

    // 设置buffer里的数据为我们的十六进制数字
    view.setUint32(0, number, false);

    // 读取浮点数
    const float = view.getFloat32(0, false);

    return Number(Math.round(float + "e+6") + "e-6").toFixed(6);
}

/**
 * ascii转16进制
 * @param {Object} str
 */
export function stringToHex(str) {
  return str.split('').map(char => char.charCodeAt(0).toString(16)).join(' ');
}

/**
 * 反转载荷
 */
export function groupStrings(str, size = 2) {
  // 检查字符串是否符合要求
  if (str.length % size !== 0) {
    throw new Error('String length needs to be a multiple of size');
  }
  // 使用整除得到数组的长度
  const length = str.length / size;
  // 使用map函数将字符串分割成指定大小的子字符串
  let arr = Array.from({ length }, (_, i) => str.substr(i * size, size));
  arr.reverse()
  return arr.join("");
}

/**
 * 打开蓝牙
 */
export function openBluetooth() {
	// 在uniapp中调用
	if (uni.getSystemInfoSync().platform === 'android') {
	  turnOnBluetoothOnAndroid();
	} else if (uni.getSystemInfoSync().platform === 'ios') {
	  turnOnBluetoothOniOS();
	}
}

/**
 * android打开蓝牙
 */
export function turnOnBluetoothOnAndroid() {
  const main = plus.android.runtimeMainActivity();
  const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter');
  const bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  if (!bluetoothAdapter.isEnabled()) {
    // 请求打开蓝牙
    const Intent = plus.android.importClass('android.content.Intent');
    const enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    main.startActivity(enableBtIntent);
  }
}

/**
 * ios打开蓝牙
 */
export function turnOnBluetoothOniOS() {
  const CBCentralManagerStatePoweredOn = 2; // CBCentralManager对象中的蓝牙开启状态
  const centralManager = new plus.ios.CBCentralManager();
  if (centralManager.state !== CBCentralManagerStatePoweredOn) {
    // 请求打开蓝牙
    centralManager.setStateOn();
  }
}